 

package uk.co.foocode.sample.petclinic.web.filter;

import java.io.ByteArrayOutputStream;
import java.io.IOException;
import java.util.Date;

import javax.servlet.FilterChain;
import javax.servlet.ServletException;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import net.sf.ehcache.constructs.web.GenericResponseWrapper;

import org.apache.commons.lang.time.DateUtils;
import org.springframework.web.filter.OncePerRequestFilter;

/**
 * A simple filter that sets the cache headers to a future date 
 *  @author Louis Emmett
  */
public class CacheHeaderFilter extends OncePerRequestFilter {
   
    /**
     *
     * @param request the current request
     * @param response the current response
     * @param chain the filter chain
     * @throws IOException
     * @throws ServletException
     */
    public void doFilterInternal(HttpServletRequest request, HttpServletResponse response,
                                 FilterChain chain) throws IOException, ServletException {

     	logger.debug("Executing cache header filter");
    	Date expiry = DateUtils.addYears(new Date(System.currentTimeMillis()), 10);
    	
    	Date shortExpiry = DateUtils.addDays(new Date(System.currentTimeMillis()), 1);

    	// set javascript to have a shorter expiry time as it's more likely to change 
    	if(request.getRequestURI().indexOf(".js")>0) {
 //   		expiry=shortExpiry;
    	}
		ByteArrayOutputStream outputStream = new ByteArrayOutputStream();
		GenericResponseWrapper wrappedResponse = new GenericResponseWrapper(
				response, outputStream);
		chain.doFilter(request, wrappedResponse);    
		if(!wrappedResponse.isCommitted()) {
			response.setDateHeader("Expires", expiry.getTime());
			// handle 304 cases with no content
			if (wrappedResponse.getStatus() != HttpServletResponse.SC_OK) {
				logger.debug("Not processing- Got Response Code "
						+ wrappedResponse.getStatus());
				if(wrappedResponse.getStatus()!= HttpServletResponse.SC_NOT_MODIFIED) {
					response.getOutputStream().write(outputStream.toByteArray());
				}
				return;
			}
			response.setHeader("Cache-control","public");
			response.getOutputStream().write(outputStream.toByteArray());
		}
    }
    
/* (non-Javadoc)
 * @see org.springframework.web.filter.OncePerRequestFilter#shouldNotFilter(javax.servlet.http.HttpServletRequest)
 */
protected boolean shouldNotFilter(HttpServletRequest request) throws ServletException {
	return request.getRequestURI().indexOf("/dwr/")!=-1 && !request.getRequestURI().endsWith("static.js");
}
}